/**
 * @sort 1
 * @name 产品信息
 */

const { api, resp } = require("apite")
const { getProducts } = require("../service/product")
const { getLength } = require("../service/common")

/**
 * @name 产品列表
 * @param {number} pageSize 每页大小
 * @param {number} pageNum 第几页，默认从一开始
 */
api.get("/api/product/list", async (ctx) => {
	const { pageNum, pageSize } = ctx.query

	try {
		const numb = pageNum > 0 ? Number(pageNum) : 1
		const size = pageSize > 0 ? Number(pageSize) : 5

		const data = await getProducts(false, {
			pageNum: numb,
			pageSize: size
		})

		const total = await getLength("products", [])

		ctx.body = resp.list(data, total, { pageNum: numb, pageSize: size })
	} catch (error) {
		ctx.body = resp.fail("error")
	}
})

/**
 * @name 产品详情
 * @param {number,string} id 数据的唯一值
 * @param {string} dealerId 经销商id，用于查看代理产品
 */
api.get("/api/product/detail", async (ctx) => {
	const { id, dealerId } = ctx.query
	if (!id) {
		ctx.body = resp.fail("请传递ID属性")
		return
	}
	const numbId = Number(id)
	try {
		const data = await getProducts(true, { id: numbId, dealerId })

		const result = data[0]

		if (result.isAccept === "1") {
			result.isAccept = true
		} else {
			result.isAccept = false
		}

		ctx.body = resp.ok(result)
	} catch (error) {
		ctx.body = resp.fail(error)
	}
})
